package com.ruyidd.controller;

import cn.databytes.btw.*;
import com.jacob.activeX.ActiveXComponent;
import com.ruyidd.consts.BartenderConsts;
import com.ruyidd.entity.BartenderParams;
import com.ruyidd.entity.EmbeddedData;
import com.ruyidd.entity.R;
import com.ruyidd.threads.BartenderPrintThread;
import com.ruyidd.utils.BartenderUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Base64;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/bartender")
public class BartenderPrintController {
    @ResponseBody
    @GetMapping("/checkBartenderInstalled")
    public R checkBartenderInstalled() {
        ActiveXComponent btApp = null;
        try{
            btApp = BartenderUtils.getActiveXComponent();
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }finally {
            BartenderUtils.closeActiveXComponent(btApp);
        }
        return R.ok("当前电脑已经安装了Bartender");
    }

    @ResponseBody
    @PostMapping("/print")
    public R print(@RequestBody BartenderParams bartenderParams) throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        log.info("同步打印参数：" + bartenderParams);
        String btwAbsolutePath = bartenderParams.getPath() + File.separator + bartenderParams.getBtwName();
        File btwFile = new File(btwAbsolutePath);
        if (!btwFile.exists()) {
            throw new RuntimeException("模板文件不存在:" + btwAbsolutePath);
        }
        if (BartenderConsts.DATA_TYPE_EMBEDED.equals(bartenderParams.getDataType())){
            BartenderUtils.embeddedDataPrint(bartenderParams);
        } else {
            BartenderUtils.txtDataPrint(bartenderParams);
        }
        stopWatch.stop();
        log.info("同步打印完成，耗时{}秒", stopWatch.getTotalTimeSeconds());
        return R.ok("打印成功！");
    }

    @ResponseBody
    @PostMapping("/singletonPrint")
    public R singletonPrint(@RequestBody BartenderParams bartenderParams) throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        log.info("同步单实例打印参数：" + bartenderParams);
        String btwAbsolutePath = bartenderParams.getPath() + File.separator + bartenderParams.getBtwName();
        File btwFile = new File(btwAbsolutePath);
        if (!btwFile.exists()) {
            throw new RuntimeException("模板文件不存在:" + btwAbsolutePath);
        }
        if (BartenderConsts.DATA_TYPE_EMBEDED.equals(bartenderParams.getDataType())){
            BartenderUtils.embeddedDataPrintSingleton(bartenderParams);
        } else {
            BartenderUtils.txtDataPrintSingleton(bartenderParams);
        }
        stopWatch.stop();
        log.info("同步单实例打印完成，耗时{}秒", stopWatch.getTotalTimeSeconds());
        return R.ok("打印成功！");
    }


    /**
     * 异步打印
     * @param bartenderParams
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/asynchronousPrinting")
    public R asynchronousPrinting(@RequestBody BartenderParams bartenderParams) throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        log.info("异步打印参数：" + bartenderParams);
        /**
         * 校验btw模板文件是否存在
         */
        BartenderUtils.checkBtwFileExisted(bartenderParams);
        BartenderPrintThread bartenderPrintThread = new BartenderPrintThread(bartenderParams);
        bartenderPrintThread.start();
        stopWatch.stop();
        log.info("异步打印完成，耗时{}秒", stopWatch.getTotalTimeSeconds());
        return R.ok("已将打印任务发送至打印机队列");
    }

    /**
     * 打印预览
     * @param bartenderParams
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/printPreview")
    public R printPreview(@RequestBody BartenderParams bartenderParams) throws Exception {
        String base64Str = "data:image/png;base64,";
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        log.info("打印预览参数：" + bartenderParams);
        String btwAbsolutePath = bartenderParams.getPath() + File.separator + bartenderParams.getBtwName();
        File btwFile = new File(btwAbsolutePath);
        if (!btwFile.exists()) {
            throw new RuntimeException("模板文件不存在:" + btwAbsolutePath);
        }
        if (BartenderConsts.DATA_TYPE_EMBEDED.equals(bartenderParams.getDataType())){
            try (IBarTenderPrintService printService = new BarTenderPrintService()) {
                // 打开btw格式模板
                ITemplate template = printService.openTemplate(btwAbsolutePath, StringUtils.isEmpty(bartenderParams.getPrinter())?"":bartenderParams.getPrinter());
                /**
                 * 嵌入式数据源
                 */
                List<EmbeddedData> embeddedDataList = bartenderParams.getEmbeddedDataList();
                if(embeddedDataList!=null&&!embeddedDataList.isEmpty()){
                    EmbeddedData embeddedData = embeddedDataList.get(0);
                    INamedSubStrings namedSubStrings = template.getNamedSubStrings();
                    for (int i = 0; i < namedSubStrings.getCount(); i++) {
                        String name = namedSubStrings.getSubString(i + 1).getName();
                        template.setData(name, embeddedData.get(name));
                    }
                    // 打印参数配置
                    IPrintSetup printSetup = template.getPrintSetup();
                    // 设置打印份数
                    if(bartenderParams.getIdenticalCopiesOfLabel()!=null&&bartenderParams.getIdenticalCopiesOfLabel()>0){
                        printSetup.setIdenticalCopiesOfLabel(bartenderParams.getIdenticalCopiesOfLabel());
                    }

                    if(bartenderParams.getNumberSerializedLabels()!=null&&bartenderParams.getNumberSerializedLabels()>0){
                        printSetup.setNumberSerializedLabels(bartenderParams.getNumberSerializedLabels());
                    }
                    try (ByteArrayOutputStream byteArrayOutputStream = template.exportToImageOutputStream();){
                        Base64.Encoder encoder = Base64.getEncoder();
                        base64Str += encoder.encodeToString(byteArrayOutputStream.toByteArray());
                    }
                }
            }
        } else {
            throw new RuntimeException("打印预览，txt数据源暂不支持");
        }
        stopWatch.stop();
        log.info("打印预览完成，耗时{}秒", stopWatch.getTotalTimeSeconds());
        R ok = R.ok("打印预览成功！");
        ok.data("base64Str", base64Str);
        return ok;
    }
}
